package com.dnjn.mes.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.mes.biz.domain.MesRecordExcept;
import com.dnjn.mes.biz.domain.MesResolvePlan;
import com.dnjn.mes.biz.domain.vo.RecordExceptPlanId;
import com.dnjn.mes.biz.enums.ExceptStatus;
import com.dnjn.mes.biz.service.IMesRecordExceptService;
import com.dnjn.mes.common.core.controller.BaseController;
import com.dnjn.mes.common.core.domain.AjaxResult;
import com.dnjn.mes.common.core.domain.R;
import com.dnjn.mes.common.utils.DateUtils;
import com.dnjn.mes.common.utils.StringUtils;
import com.dnjn.mes.common.utils.poi.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 异常报警表，正确状态不写入 前端控制器
 * </p>
 *
 * @author Amber
 * @since 2023-07-26
 */
@RestController
@RequestMapping("/biz/mesRecordExcept")
public class MesRecordExceptController extends BaseController {

    @Autowired
    protected IMesRecordExceptService baseService;

    @GetMapping("/get/{id}")
    public AjaxResult get(@PathVariable Long id) {
        return success(baseService.getById(id));
    }

    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody MesRecordExcept domain) {
        domain.setCreateBy(getUsername());
        return toAjax(baseService.save(domain));
    }

    @PutMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody MesRecordExcept domain) {
        return toAjax(baseService.updateById(domain));
    }

    @DeleteMapping("/{pkIds}")
    public AjaxResult remove(@PathVariable Long[] pkIds) {
        baseService.removeBatchByIds(Arrays.asList(pkIds));
        return success();
    }

    @PostMapping("/page")
    public AjaxResult page(@RequestBody MesRecordExcept domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page page = Page.of(current, size);
        Page<MesRecordExcept> list = baseService.page(page, Wrappers.query(domain));
        return success(list);
    }

    @PostMapping("/export")
    public void export(HttpServletResponse response, MesRecordExcept domain) {
        List<MesRecordExcept> list = baseService.list(Wrappers.query(domain));
        ExcelUtil<MesRecordExcept> util = new ExcelUtil<MesRecordExcept>(MesRecordExcept.class);
        util.exportExcel(response, list, "参数数据");
    }


    /**
     * 更新未处理的故障，关联解决方案，更新故障关联方案及状态
     * Params
     * recordExceptId: 故障id,
     * planId: 方案id,
     * exceptId: 异常id,
     *
     * public R updateRecordStatus(@RequestParam("recordExceptId") Long recordExceptId, @RequestParam("exceptId") Long exceptId,
     *                                 @RequestParam("planIds") Long[] planIds,@RequestHeader(value = "equipmentId") long equipmentId) {
     */

    @Operation(summary = "更新未处理的故障")
    @PutMapping("/updateRecordStatus")
    public R updateRecordStatus(@Validated @RequestBody RecordExceptPlanId vo, @RequestHeader(value = "equipmentId") long equipmentId) {
        /*if (Objects.isNull(recordExceptId) || Objects.isNull(exceptId)) {
            return R.fail("recordExceptId或exceptId不能为空！");
        }*/
        if(null == vo.getPlanIds() || vo.getPlanIds().length <= 0){
            return R.fail("方案不能为空！");
        }
        //计算duration_hour 时间差
        return R.ok(baseService.updateRecordStatus(vo,equipmentId));
    }


    /**
     * 故障维修统计->统计每天故障次数
     * startTime: 2023-08-22
     * endTime: 2023-09-01
     */
    @Operation(summary = "统计每天故障次数",tags = {"数据统计"})
    @PostMapping("/countRecordExcepts")
    public AjaxResult countRecordExcepts(@RequestParam(required = false) @Parameter(description = "yyyy-MM-dd") String startTime, @RequestParam(required = false) @Parameter(description = "yyyy-MM-dd") String endTime,
                                         @RequestHeader(value = "equipmentId") long equipmentId) {
        //如果两个日期为空时，默认获取当前日期前一个月的
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            LocalDateTime endLocalDateTime = LocalDateTime.now();
            LocalDateTime startLocalDateTime = LocalDateTime.now().minusMonths(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            startTime = formatter.format(startLocalDateTime);
            endTime = formatter.format(endLocalDateTime);
        }
        List<MesRecordExcept> recordExceptList = baseService.countRecordExcepts(startTime, endTime, equipmentId);
        return success(recordExceptList);
    }

    /**
     * 故障维修统计->统计每天维修时间
     * startTime: 2023-08-22
     * endTime: 2023-09-01
     */
    @Operation(summary = "统计每天维修时间",tags = {"数据统计"})
    @PostMapping("/countMaintenanceTime")
    public AjaxResult countMaintenanceTime(@RequestParam(required = false) @Parameter(description = "yyyy-MM-dd") String startTime, @RequestParam(required = false) @Parameter(description = "yyyy-MM-dd") String endTime,
                                           @RequestHeader(value = "equipmentId") long equipmentId) {
        //如果两个日期为空时，默认获取当前日期前一个月的
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            LocalDateTime endLocalDateTime = LocalDateTime.now();
            LocalDateTime startLocalDateTime = LocalDateTime.now().minusMonths(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            startTime = formatter.format(startLocalDateTime);
            endTime = formatter.format(endLocalDateTime);
        }
        List<MesRecordExcept> recordExceptList = baseService.countMaintenanceTime(startTime, endTime, equipmentId);
        return success(recordExceptList);
    }

    /**
     * 故障维修统计-> 故障分类统计
     * startTime: 2023-08-22
     * endTime: 2023-09-01
     */
    @Operation(summary = "故障分类统计",tags = {"数据统计"})
    @PostMapping("/recordExceptCit")
    public AjaxResult recordExceptCit(@RequestParam(required = false) @Parameter(description = "yyyy-MM-dd") String startTime, @RequestParam(required = false) @Parameter(description = "yyyy-MM-dd") String endTime,
                                           @RequestHeader(value = "equipmentId") long equipmentId) {
        //如果两个日期为空时，默认获取当前日期前一个月的
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            LocalDateTime endLocalDateTime = LocalDateTime.now();
            LocalDateTime startLocalDateTime = LocalDateTime.now().minusMonths(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            startTime = formatter.format(startLocalDateTime);
            endTime = formatter.format(endLocalDateTime);
        }
        List<MesRecordExcept> recordExceptList = baseService.recordExceptCit(startTime, endTime, equipmentId);
        return success(recordExceptList);
    }


    /**
     * 数据统计->故障报警记录
     */
    @Operation(summary = "故障报警记录",tags = {"数据统计"})
    @PostMapping("/faultAlarmRecord")
    public AjaxResult faultAlarmRecord(@RequestParam(defaultValue = "1") Integer current,
                                       @RequestParam(defaultValue = "10") Integer size,
                                       @RequestParam(required = false) String exceptMessageCn, @RequestHeader(value = "equipmentId") long equipmentId) {
        PageHelper.startPage(current, size);
        List<MesRecordExcept> recordExceptList = baseService.faultAlarmRecord(equipmentId, exceptMessageCn);
        PageInfo pageInfo = new PageInfo(recordExceptList);
        return success(pageInfo);
    }




}